<?php

namespace app\common;

use \app\common\Guzzle;

Class Ocr {

	public static function idcard($side, $filename)
	{

		$sides = ['face', 'back'];
		$md5 = hash_file('md5', $filename);
		$value = model('Ocr')->get_one(['md5' => $md5 ]);
		if($value) {
			return json_decode($value['body'], true);
		}
		$client = Guzzle::client();
		$appcode = model('Config')->config('aliyun_appcode');
		$res = $client->post('https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json', [
			'headers' => [
				'Authorization' => 'APPCODE ' . $appcode,
				'Content-Type' => 'application/json; charset=UTF-8',
			],
			'body' => json_encode([
				'image' => base64_encode(file_get_contents($filename)),
				'configure' => ['side' => $side],
			]),
		]);
		$body = $res->getBody()->getContents();
		$result = json_decode($body, true);
		if($result) {
			model('Ocr')->allowField(true)->save([
				'md5' => $md5,
				'body' => $body,
			]);
			return $result;
		} else {
			return $res->getBody()->getContents();
		}

	}

	public static function business_license($filename)
	{

		$md5 = hash_file('md5', $filename);
		$value = model('Ocr')->get_one(['md5' => $md5 ]);
		if($value) {
			return json_decode($value['body'], true);
		}
		$client = Guzzle::client();
		$appcode = model('Config')->config('aliyun_appcode');
		$res = $client->post('https://dm-58.data.aliyun.com/rest/160601/ocr/ocr_business_license.json', [
			'headers' => [
				'Authorization' => 'APPCODE ' . $appcode,
				'Content-Type' => 'application/json; charset=UTF-8',
			],
			'body' => json_encode([
				'image' => base64_encode(file_get_contents($filename)),
			]),
		]);
		$body = $res->getBody()->getContents();
		$result = json_decode($body, true);
		if($result) {
			model('Ocr')->allowField(true)->save([
				'md5' => $md5,
				'body' => $body,
			]);
			return $result;
		} else {
			return $res->getBody()->getContents();
		}

	}

}

